import { request } from '@umijs/max';
import { qiniuConfig, QiniuTokenResponse } from '../../config/qiniu';

// 七牛上传token接口
export async function getUploadKey(params: {
  type?: string;
  upload_type?: string;
  bucket?: string;
  key?: string; // 添加key参数
  mimeType?: string; // 添加MIME类型参数
}): Promise<QiniuTokenResponse> {
  return request(qiniuConfig.tokenApi, {
    method: 'get',
    params: {
      ...params,
      bucket: params.bucket || qiniuConfig.bucket,
    },
  });
}

// 七牛上传文件
export async function uploadToQiniu(file: File, token: string, key: string): Promise<Response> {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('token', token);
  formData.append('key', key);

  return fetch(qiniuConfig.uploadUrl, {
    method: 'POST',
    body: formData,
  });
}

// 构建七牛文件URL
export function buildQiniuUrl(key: string): string {
  return `${qiniuConfig.domain}/${key}`;
}

export default {
  getUploadKey,
  uploadToQiniu,
  buildQiniuUrl,
};
